﻿using Microsoft.Win32;
using System;
using System.IO;
using System.Linq;
using System.Reflection;


namespace NFox.Cad.Runtime
{

    public enum AssemLoadType
    {
        Startting = 2,
        ByCommand = 12,
        Disabled = 20
    }
    
    public abstract class AutoRegAssem : Autodesk.AutoCAD.Runtime.IExtensionApplication
    {

        private AssemInfo _info = new AssemInfo();

        public FileInfo Location
        {
            get { return new FileInfo(Assembly.GetCallingAssembly().Location); }
        }

        public DirectoryInfo CurrDirectory
        {
            get { return Location.Directory; }
        }

        public DirectoryInfo GetDirectory(Assembly assem)
        {
            return new FileInfo(assem.Location).Directory;
        }



        public AutoRegAssem()
        {

            Assembly assem = Assembly.GetCallingAssembly();
            _info.Loader = assem.Location;
            _info.Fullname = assem.FullName;
            _info.Name = assem.GetName().Name;
            _info.LoadType = AssemLoadType.Startting;

            if (!SearchForReg())
            {
                RegApp();
            }

        }


        #region RegApp

        private RegistryKey GetAcAppKey()
        {
            string key =
                Autodesk
                .AutoCAD
                .DatabaseServices
                .HostApplicationServices
                .Current
                .MachineRegistryProductRootKey;
            RegistryKey ackey =
                Registry.CurrentUser.OpenSubKey(key, true);
            return ackey.CreateSubKey("Applications");
        }

        private bool SearchForReg()
        {
            RegistryKey appkey = GetAcAppKey();
            var regApps = appkey.GetSubKeyNames();
            return regApps.Contains(_info.Name);
        }

        public void RegApp()
        {
            RegistryKey appkey = GetAcAppKey();
            RegistryKey rk = appkey.CreateSubKey(_info.Name);
            rk.SetValue("DESCRIPTION", _info.Fullname, RegistryValueKind.String);
            rk.SetValue("LOADCTRLS", _info.LoadType, RegistryValueKind.DWord);
            rk.SetValue("LOADER", _info.Loader, RegistryValueKind.String);
            rk.SetValue("MANAGED", 1, RegistryValueKind.DWord);
            appkey.Close();
        }

        #endregion

        #region IExtensionApplication 成员

        public abstract void Initialize();

        public abstract void Terminate();

        #endregion

    }
}

